package com.goldenautumn.prefabricate.activity.mine.order

import android.graphics.Paint
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SizeUtils
import com.goldenautumn.prefabricate.MainActivity
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.cart.SettlementActivity
import com.goldenautumn.prefabricate.activity.cart.SettlementGoodsAdapter
import com.goldenautumn.prefabricate.activity.mine.adapter.OrderItemAdapter
import com.goldenautumn.prefabricate.business.entity.AddressInfoVo
import com.goldenautumn.prefabricate.business.entity.ApplyRefundGoods
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsSkuVo
import com.goldenautumn.prefabricate.business.entity.OrderDetailsInfoVo
import com.goldenautumn.prefabricate.business.entity.OrderInfoVo
import com.goldenautumn.prefabricate.business.mall.GoodsInfoUiState
import com.goldenautumn.prefabricate.business.mall.MallViewModel
import com.goldenautumn.prefabricate.business.order.OrderListUiState
import com.goldenautumn.prefabricate.business.order.OrderStatusUiState
import com.goldenautumn.prefabricate.business.order.OrderViewModel
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.databinding.ActivityOrderDetailsBinding
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.gone
import qncx.external.common.compat.isVisible
import qncx.external.common.compat.visible
import qncx.external.common.utils.intent
import qncx.external.common.widget.dialog.PromptDialog

class OrderDetailsActivity : BaseActivity<ActivityOrderDetailsBinding>() {

    private val mOrderModel by viewModels<OrderViewModel>()

    private val mMallModel by viewModels<MallViewModel>()

    private var orderDetails: OrderDetailsInfoVo? = null

    private val mAdapter by lazy {
        SettlementGoodsAdapter(2)
    }

    var launcher =  registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if(result.resultCode == RESULT_OK) {
            mOrderModel.onOrderDetails("$orderID")
        }
    }

    private val orderID:String?
        get() = intent.getStringExtra(BUSINESS_PAGE_DATA)

    override fun getLayoutId(): Int = R.layout.activity_order_details

    override suspend fun main() {
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        initToolbarNav(mBinding.toolbar,true)
        setFlags(mBinding.orderAction)
        setFlags(mBinding.goodsAction)
        setFlags(mBinding.totalAction)

        mBinding.goodsRv.layoutManager = LinearLayoutManager(this)
        mBinding.goodsRv.adapter = mAdapter

        mBinding.totalAction.setOnClickListener {
            mBinding.totalBody.isVisible(!mBinding.totalBody.isVisible)
            mBinding.totalAction.text = if(mBinding.totalBody.isVisible) getString(R.string.hide) else getString(R.string.show)
        }

        mBinding.orderAction.setOnClickListener {
            mBinding.orderInfo.isVisible(!mBinding.orderInfo.isVisible)
            mBinding.orderAction.text = if(mBinding.orderInfo.isVisible) getString(R.string.hide) else getString(R.string.show)
        }


        mBinding.totalAction.setOnClickListener {
            mBinding.totalBody.isVisible(!mBinding.totalBody.isVisible)
            mBinding.totalAction.setText(if(mBinding.totalBody.isVisible) R.string.hide else R.string.show)
        }

        mBinding.orderAction.setOnClickListener {
            mBinding.orderInfo.isVisible(!mBinding.orderInfo.isVisible)
            mBinding.orderAction.setText(if(mBinding.orderInfo.isVisible) R.string.hide else R.string.show)
        }

        mBinding.orderSn.setOnClickListener {
            ClipboardUtils.copyText(mBinding.orderSn.text.toString())
            onCenterToast(getString(qncx.external.common.R.string.common_copy))
        }

        mAdapter.addOnItemChildClickListener(R.id.actionBtn) { adapter,_,position ->
            var item = adapter.getItem(position)
            var data = ApplyRefundGoods(
                goods_id = item?.goods_id,
                goods_image = item?.goods_image,
                goods_name = item?.goods_name,
                goods_sku = GoodsSkuVo(goods_attr = item?.goods_sku?.goods_attr,goods_price = item?.goods_sku?.goods_price, spec_sku_id = item?.goods_sku?.spec_sku_id),
                total_num = item?.total_num,
            )
            launcher.launch(ApplyRefundActivity::class.intent.putExtra("DATA",data).putExtra(BUSINESS_PAGE_DATA,orderDetails?.order_no))
        }

        mBinding.lookLogistics.setOnClickListener {
            startActivity(LogisticsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,"$orderID"))
        }

        mOrderModel.onOrderDetails("$orderID")

        while (isActive) {
            select {
                mOrderModel.loading.onReceive {
                    when (it) {
                        is LoadingUiState.LoadingUI -> {
                            if(!it.isShow) mBinding.mLoading.gone()
                            else {}
                        }
                        else -> {}
                    }
                }
                mMallModel.goodsDetailsRequests.onReceive {
                    when (it) {
                        is GoodsInfoUiState.GoodsAddCar -> {
                            if(it.msg == null) addSuccess()
                            else onCenterToast(it.msg ?: "")
                        }
                        else -> {}
                    }
                }
                mOrderModel.orderStatusUiState.onReceive {
                    when (it) {
                        is OrderStatusUiState.OrderDetails -> {
                            orderDetails = it.order
                            orderDetails?.let {
                                mBinding.name.text = it.address?.name
                                mBinding.phone.text = it.address?.phone
                                mBinding.address.text = it.address?.detail
                                mBinding.province.text = "${it.address?.region?.province},${it.address?.region?.city},${it.address?.region?.region}"
                            }
                            it.order?.let { details ->
                                when(details.order_status?.value) {
                                    "30" -> { //已完成
                                        mBinding.orderStatus.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this@OrderDetailsActivity, R.mipmap.ic_order_status_finish),null, null, null)
                                        mBinding.orderStatus.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.colorPrimary))
                                        mBinding.orderStatus.setText(R.string.order_status_complete)
                                        mBinding.actionBtnLeft.gone()
                                        mBinding.actionBtnRight.visible()
                                        mBinding.lookLogistics.visible()
                                        mBinding.actionBtnLeft.setText(R.string.order_action_after_sales)
                                        mBinding.actionBtnRight.setText(R.string.order_action_repurchase)
                                        mBinding.statusDec.text = getString(R.string.order_fisnih_msg)
                                        val layoutParams = mBinding.actionBtnRight.layoutParams as ViewGroup.MarginLayoutParams
                                        layoutParams.setMargins(
                                            SizeUtils.dp2px(16f),
                                            SizeUtils.dp2px(16f),SizeUtils.dp2px(16f),
                                            SizeUtils.dp2px(16f))
                                        mBinding.actionBtnRight.layoutParams = layoutParams
                                        mBinding.actionBtnRight.shapeBuilder
                                            ?.setShapeSolidColor(ContextCompat.getColor(this@OrderDetailsActivity, qncx.external.common.R.color.white))
                                            ?.setShapeStrokeColor(ContextCompat.getColor(this@OrderDetailsActivity, qncx.external.common.R.color.color_cccccc))
                                            ?.setShapeStrokeWidth(4)?.into(mBinding.actionBtnRight)
                                        mBinding.actionBtnRight.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.color_1D1F20))
                                        mBinding.actionBtnLeft.setOnClickListener {
                                            startActivity(ApplyRefundActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,orderID))
                                        }
                                        mBinding.actionBtnRight.setOnClickListener {
                                            addCarGoods()
                                        }
                                    }
                                    "21","20" -> { //待取消(已付款)  / 已取消
                                        mBinding.orderStatus.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this@OrderDetailsActivity, R.mipmap.ic_order_status_cancel),null, null, null)
                                        mBinding.orderStatus.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.color_1D1F20))
                                        mBinding.orderStatus.setText(R.string.order_status_after_cancel)
                                        mBinding.actionBtnLeft.setText(R.string.order_action_repurchase)
                                        mBinding.actionBtnLeft.visible()
                                        mBinding.actionBtnRight.gone()
                                        mBinding.statusDec.text = getString(R.string.order_cancel_msg)
                                        mBinding.actionBtnLeft.setOnClickListener {
                                            addCarGoods()
                                        }
                                    }
                                    "10" -> { //其他状态
                                        if(details.pay_status?.value == "20") { //已支付
                                            if(details.delivery_status?.value == "10") { //待发货
                                                mBinding.orderStatus.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this@OrderDetailsActivity, R.mipmap.ic_order_status_shipments),null, null, null)
                                                mBinding.orderStatus.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.color_F48A02))
                                                mBinding.orderStatus.setText(R.string.order_status_shipment)
                                                mBinding.actionBtnLeft.setText(R.string.order_action_apply_cancel)
                                                mBinding.actionBtnLeft.visible()
                                                mBinding.actionBtnRight.gone()
                                                mBinding.statusDec.text = getString(R.string.order_shipped_msg)
                                                mBinding.actionBtnLeft.setOnClickListener {
                                                    setOrderCanCel(details.order_id)
                                                }
                                            } else { //已发货
                                                mBinding.orderStatus.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this@OrderDetailsActivity, R.mipmap.ic_order_status_receiving),null, null, null)
                                                mBinding.orderStatus.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.colorPrimary))
                                                mBinding.orderStatus.setText(R.string.order_status_receiving)
                                                mBinding.actionBtnRight.setText(R.string.order_action_confirm_receipt)
                                                mBinding.actionBtnLeft.setText(R.string.order_action_after_sales)
                                                mBinding.actionBtnLeft.gone()
                                                mBinding.actionBtnRight.visible()
                                                val layoutParams = mBinding.actionBtnRight.layoutParams as ViewGroup.MarginLayoutParams
                                                layoutParams.setMargins(
                                                    SizeUtils.dp2px(16f),
                                                    SizeUtils.dp2px(16f),SizeUtils.dp2px(16f),
                                                    SizeUtils.dp2px(16f))
                                                mBinding.actionBtnRight.layoutParams = layoutParams
                                                mBinding.lookLogistics.visible()
                                                mBinding.actionBtnRight.shapeBuilder
                                                    ?.setShapeSolidColor(ContextCompat.getColor(this@OrderDetailsActivity, qncx.external.common.R.color.white))
                                                    ?.setShapeStrokeColor(ContextCompat.getColor(this@OrderDetailsActivity, qncx.external.common.R.color.color_cccccc))
                                                    ?.setShapeStrokeWidth(4)?.into(mBinding.actionBtnRight)
                                                mBinding.actionBtnRight.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.color_1D1F20))
                                                mBinding.statusDec.text = getString(R.string.order_receiving_msg)
                                                mBinding.actionBtnLeft.setOnClickListener {
                                                    startActivity(ApplyRefundActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,orderID))
                                                }
                                                mBinding.actionBtnRight.setOnClickListener {
                                                    receivingGoods()
                                                }
                                            }
                                        } else {
                                            mBinding.orderStatus.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this@OrderDetailsActivity, R.mipmap.ic_order_status_wait),null, null, null)
                                            mBinding.orderStatus.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity,R.color.color_DE0000))
                                            mBinding.orderStatus.setText(R.string.order_status_pending)
                                            mBinding.actionBtnLeft.setText(R.string.order_action_cancel)
                                            mBinding.actionBtnLeft.visible()
                                            mBinding.actionBtnRight.visible()
                                            mBinding.actionBtnRight.setText(R.string.order_action_pay)
                                            mBinding.statusDec.text = getString(R.string.order_paid_msg)
                                            mBinding.actionBtnLeft.setOnClickListener {
                                                setOrderCanCel(details.order_id)
                                            }
                                            mBinding.actionBtnRight.setOnClickListener {
                                                startActivity(SettlementActivity::class.intent.putExtra("ORDER","${details?.order_id}"))
                                            }
                                        }
                                    }
                                }

                                var isShowRefund = false
                                if(orderDetails?.order_status?.value == "30") isShowRefund = true
                                else if(orderDetails?.order_status?.value == "10" && details.delivery_status?.value == "20") isShowRefund = true
                                var goods = ArrayList<GoodsInfoVO>()
                                details.goods?.forEach {
                                    goods.add(
                                        GoodsInfoVO(
                                        goods_id = it.order_goods_id,
                                        goods_image = it.image?.file_path,
                                        goods_name = it.goods_name,
                                        goods_sku = GoodsSkuVo(goods_attr = it.goods_attr,goods_price = it?.goods_price, spec_sku_id = it?.spec_sku_id),
                                        total_num = it.total_num,
                                        content = "$isShowRefund",
                                    )
                                    )
                                }

                                mAdapter.submitList(goods)
                                mBinding.price.text = "${(String.format(getString(R.string.currency), "${it.order.total_price}"))}"
                                mBinding.subtotal.text = "${(String.format(getString(R.string.currency), "${it.order?.order_price}"))}"
                                mBinding.totalPrice.text = "${(String.format(getString(R.string.currency), "${it.order?.pay_price}"))}"
                                mBinding.freight.text = "${(String.format(getString(R.string.currency), "${it.order?.express_price}"))}"
                                mBinding.preferential.text = "${if((it.order?.coupon_money ?:"0L").toFloat() > 0) "-${(String.format(getString(R.string.currency), "${it.order?.coupon_money}"))}" else "0"}"

                                mBinding.orderSn.text = "${details.order_no}"
                                mBinding.orderTime.text = "${details.create_time}"
                                mBinding.orderPay.text = "${details.pay_type?.text}"
                                mBinding.orderDelivery.text = "${details.delivery_type?.text}"

                            }
                        }
                        is OrderStatusUiState.ActionMsg -> {
                            if(it.msg != null) onCenterToast("${it.msg}")
                            else mOrderModel.onOrderDetails("$orderID")
                        }
                        else -> {}
                    }
                }

            }
        }
    }

    fun setFlags(view:TextView){
        view.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        view.paint.isAntiAlias = true
    }

    fun setOrderCanCel(ids:String?){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.cancel_order))
                view.setShowCancel(true)
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    mOrderModel.onOrderCanCel("${ids}",0)
                }
            }
        }).onShow(supportFragmentManager.beginTransaction())
    }

    fun addCarGoods(){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.order_add_car))
                view.setShowCancel(true)
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    mMallModel.addCarBatch(mAdapter.items)
                }
            }
        }).onShow(supportFragmentManager.beginTransaction())
    }

    fun receivingGoods(){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.order_receipt_msg))
                view.setShowCancel(true)
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    mOrderModel.onOrderReceiving("$orderID")
                }
            }
        }).onShow(supportFragmentManager.beginTransaction())
    }

    fun addSuccess(){
        PromptDialog().setConfirmListener(object : PromptDialog.ConfirmHandleListener {
            override fun bindView(dialog: PromptDialog, view: PromptDialog.PromptModel) {
                view.setMsgText(getString(R.string.added_cart))
                view.setShowCancel(true)
                view.setConfirmText(getString(R.string.go_to_car))
                view.getPromptConfirm().setOnClickListener {
                    dialog.dismiss()
                    SPUtils.getInstance().put("home",2)
                    startActivity(MainActivity::class.intent)
                }
            }
        }).onShow(supportFragmentManager.beginTransaction())
    }

}